<template>
  <van-form @submit="handleBind">
    <van-cell-group inset>
      <van-field
        v-model="name"
        label="联系人名称"
        placeholder="请输入联系人名称"
        :rules="[{ required: true, message: '请填写联系人名称' }]"
      />
      <van-field
        v-model="phone"
        label="手机号"
        placeholder="请输入绑定手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          立即绑定
        </van-button>
      </div>
    </van-cell-group>
  </van-form>
</template>

<script setup>
import { ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import service from "@/api";

const phone = ref("");
const name = ref("");

const route = useRoute();

// 用户openId
const openId = route.query.openId || "";
// 用户路由页,默认跳到订单页面
//const target = route.query.target || '/#/qdxt/order'
console.log(route.query);
const hash = window.location.hash;

const target = route.query.target?.includes("/list")
  ? window.location.origin + (hash ? "/#" : "") + route.query.target
  : window.location.origin + (hash ? "/#" : "") + "/query";
const handleBind = async () => {
  try {
    const res = await service.bindPhone({
      itype: "customer_bind",
      info: {
        phone: phone.value,
        username: name.value,
        openId: openId,
      },
    });
    if (res.status === "success") {
      // 存储用户信息到本地缓存
      localStorage.setItem("userInfo", JSON.stringify(res.data));
      alert("绑定成功，确定后跳转订单页面");
      //alert(target+'?openId='+openId);
      // 路由跳转到订单页面
      window.location.href = target + "?openId=" + openId;
    } else {
      alert("绑定失败" + res.message);
    }
  } catch (error) {
    //console.error('绑定请求失败：', error)
  }
};
</script>
